package pprg;

public class MandelBrotWorker implements Runnable {

	private int startRow;
	private int numRows;
	private int maxN;
	private double x0;
	private double y0;
	private double x1;
	private double y1;
	private int width;
	private int height;

	private int index;
	private int[] rgbValues;

	private static int RGB_BLACK = -16777216;

	public MandelBrotWorker(int startRow, int numRows, int maxN, double x0,
			double y0, double x1, double y1, int width, int height) {
		this.startRow = startRow;
		this.numRows = numRows;
		this.maxN = maxN;
		this.x0 = x0;
		this.x1 = x1;
		this.y0 = y0;
		this.y1 = y1;
		this.width = width;
		this.height = height;
		rgbValues = new int[width * height];
		index = 0;
		System.out.println("CREATED - Worker start at row " + startRow);
	}

	@Override
	public void run() {

		for (int row = startRow; row < startRow + numRows; row++) {
			for (int col = 0; col < width; col++) {
				calcPixel(col, row);
			}
		}
	}

	private void calcPixel(int x, int y) {

		double xFactor = (double) x / width;
		double yFactor = (double) y / height;
		double cr = (x1 - x0) * xFactor + x0;
		double ci = (y1 - y0) * yFactor + y0;
		double zr = 0;
		double zi = 0;

		for (int n = 0; n < maxN; n++) {

			double nextZr = zr * zr - zi * zi + cr;
			double nextZi = 2 * zr * zi + ci;

			if (nextZr * nextZr + nextZi * nextZi > 4) {

				rgbValues[index++] = n << 8;
				return;
			}
			zr = nextZr;
			zi = nextZi;
		}
		rgbValues[index++] = RGB_BLACK;
	}

	public int getNumRows() {
		return numRows;
	}

	public int getStartRow() {
		return startRow;
	}

	public int[] getRgbValues() {
		return rgbValues;
	}
}
